/**
 * Copyright (C) 2012 LightAsyncHttpClient Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.oc.mba.http;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

/**
 * <ul>
 * <li><b>name : </b>		SimpleResponseHandler		</li>
 * <li><b>description :</b>	简单的响应处理类				</li>
 * <li><b>author : </b>		桥下一粒砂			</li>
 * <li><b>e-mail : </b>		chenyoca@gmail.com	</li>
 * <li><b>weibo : </b>		@桥下一粒砂			</li>
 * <li><b>date : </b>		2012-10-12 下午6:29:55		</li>
 * </ul>
 */
public abstract class SimpleResponseHandler implements ResponseCallback {

	@Override
	public void onStart(String url) { }

	@Override
	final public void onSuccess(int requestId, HttpResponse response, String url) {
		final int statusCode = response.getStatusLine().getStatusCode(); 
		if( statusCode == HttpStatus.SC_OK ){
			final HttpEntity entity = response.getEntity();
			if( entity == null ) {
				onError( new Throwable("Response entity is NULL"), requestId, url );
				return;
			}
			try {
				String jsonText = EntityUtils.toString(entity, HTTP.UTF_8);
				successWithTextData(jsonText, requestId, url);
//				if (entity.getContentType() != null) {
//					String contentType = entity.getContentType().getValue();
//					if(contentType.toLowerCase().contains("text")){
//						successWithTextData(EntityUtils.toString(entity), requestId, url);
//					}else{
//						successWithBinaryData(EntityUtils.toByteArray(entity), requestId, url);
//					}
//				}
//				else {
//					successWithTextData(EntityUtils.toString(entity), requestId, url);
//				}
			} catch (Exception exp) {
				//捕获全部异常
				onError( new Throwable(exp), requestId, url);
			}
		}else{
			onError(new Throwable( String.format("Server response{status:%d} is NOT OK",statusCode) ), requestId, url);
		}
		
	}
	
	/**
	 * 如果服务端响应为 字符型 数据，则此方法被回调。
	 * @param content
	 */
	public abstract void successWithTextData(String content, int requestId, String url); 
	
	/**
	 * 如果服务端响应为 * 非字符型 数据，则此方法被回调。
	 * @param content
	 */
	public abstract void successWithBinaryData(byte[] binary, int requestId, String url);

	@Override
	public void onCancel(int requestId,String url) { }

	public static String convertToString(InputStream is,String enc) throws IOException{
	    if( null == is) return null;
		ByteArrayOutputStream buffer = new ByteArrayOutputStream();
		int IS_EOF = -1;
		while ((IS_EOF = is.read()) != -1) {
			buffer.write(IS_EOF);
		}
		is.close();
		return buffer.toString(enc);
	}
	
	/**
	 * <b>description :</b>		将InputStream转换成字节数组。
	 * @param is 				InputStream对象
	 * @return 				字节数组
	 * @throws IOException 
	 */
	public static byte[] convertToByteArray(InputStream is) throws IOException{
	    if( null == is) return null;
		byte[] cache = new byte[ 1 * 1024 ];
		ByteArrayOutputStream buffer = new ByteArrayOutputStream();
		for (int length = 0; (length = is.read(cache)) != -1;) {
		    buffer.write(cache, 0, length);
        }
		is.close();
		return buffer.toByteArray();
	}

}
